package pers.xuyong.code.lang.classloader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 网络类加载器
 *
 * @author billymac
 * @version 1.0
 * @date 17/8/1  上午11:08
 * @since JDK1.8
 */
public class NetworkClassLoader extends ClassLoader {

    private String url;

    public NetworkClassLoader(String url) {
        this.url = url;
    }

    @Override
    protected Class findClass(String name) throws ClassNotFoundException {
        Class aClass = null;
        try {
            byte[] classData = getClassData(name);
            aClass = defineClass(name, classData, 0, classData.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return aClass;
    }

    private byte[] getClassData(String name) throws IOException {
        String path = getClassPath(name);
        URL url = new URL(path);
        InputStream inputStream = url.openStream();
        byte[] buffer = new byte[1024 * 4];
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int length = 0;
        while((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        return outputStream.toByteArray();
    }

    private String getClassPath(String name) {
        return url + "/" + name.replaceAll("\\.", "/") + ".class";
    }
}
